package com.cskaoyan.service;

import com.cskaoyan.bean.reverseengineering.MarketAd;
import com.cskaoyan.bean.reverseengineering.MarketAdExample;
import com.cskaoyan.bean.bo.adbo.AdListBO;
import com.cskaoyan.bean.vo.promote.adVO.AdData;
import com.cskaoyan.mapper.MarketAdMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 创建日期: 2022/05/05 19:49
 *
 * @author yangfan
 */
// 实现Ad类
// 请求网址: http://182.92.235.201:8083/admin/ad/list?page=1&limit=20&sort=add_time&order=desc
@Service
public class AdServiceImpl implements AdService {

    @Autowired
    MarketAdMapper marketAdMapper;

    @Override
    public MarketAd create(MarketAd marketAd) {

        marketAd.setAddTime(new Date());

        marketAdMapper.insert(marketAd);

        return marketAd;
    }


    @Override
    public MarketAd update(MarketAd marketAd) {

        // 设置更新时间
        marketAd.setUpdateTime(new Date());

        MarketAdExample example = new MarketAdExample();
        example.createCriteria()
                .andIdEqualTo(marketAd.getId());

        marketAdMapper.updateByExample(marketAd,example);

        return marketAd;
    }

    @Override
    public void delete(MarketAd marketAd) {
        marketAdMapper.deleteByPrimaryKey(marketAd.getId());
    }


    @Override
    public AdData list(AdListBO adListBO) {

        MarketAdExample example = new MarketAdExample();
        MarketAdExample.Criteria criteria = example.createCriteria();

        // 排序规则
        example.setOrderByClause(adListBO.getSort() + " " + adListBO.getOrder());
        // 分页查询
        PageHelper.startPage(adListBO.getPage(),adListBO.getLimit());

        // name不空 content空
        if (adListBO.getName() != null) {
            criteria.andNameLike("%" + adListBO.getName() + "%");
        }
        // name 不空， content 空
        if (adListBO.getContent() != null) {
            criteria.andContentLike("%" + adListBO.getContent() + "%");
        }


        List<MarketAd> list = marketAdMapper.selectByExample(example);
        // 分页查询
        PageHelper.startPage(adListBO.getPage(),adListBO.getLimit());
        PageInfo<MarketAd> pageInfo = new PageInfo<>(list);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();

        AdData adData = new AdData();
        adData.setList(list);
        adData.setLimit(adListBO.getLimit());
        adData.setPage(adListBO.getPage());
        adData.setPages(pages);
        adData.setTotal((int) total);

        return adData;
    }
}
